package com.tyc.mb.config;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 类描述
 *
 * @author tyc
 * @version 1.0
 * @date 2021-10-25 18:02:10
 */
@Component("dataSourceHolder")
public class DataSourceContextHolder implements InitializingBean {
    // mysql8及以上用：com.mysql.jdbc.jdbc2.optional.MysqlXADataSource
    // mysql5用：com.mysql.jdbc.jdbc2.optional.MysqlDataSource
    private static final String DATA_SOURCE_CLASS = "com.mysql.jdbc.jdbc2.optional.MysqlDataSource";
    private static final String CONNECTION_TEST_QUERY = "SELECT 1";
    private static final ThreadLocal<Integer> dsKey = new ThreadLocal<>();

    @Autowired
    private DataSource1 dataSource1;

    @Autowired
    private DataSource2 dataSource2;

    @Autowired
    private DynamicDataSource multipleDataSource;

    @Override
    public void afterPropertiesSet() {
        Map<Object, Object> sourceMap = new HashMap();
        Map<Object, Object> d2 = addOne(dataSource2.getUrl(), dataSource2.getSid(), dataSource2.getUsername(), dataSource2.getPassword());
        Map<Object, Object> d1 = addOne(dataSource1.getUrl(), dataSource1.getSid(), dataSource1.getUsername(), dataSource1.getPassword());
        sourceMap.putAll(d1);
        sourceMap.putAll(d2);
        multipleDataSource.setTargetDataSources(sourceMap);
    }

    private Map<Object, Object> addOne(String localUrl, int sourceKey, String userName, String password) {
        Map<Object, Object> dataSourceMap = new HashMap();

        HikariDataSource hDataSource = new HikariDataSource();
        hDataSource.setDataSourceClassName(DATA_SOURCE_CLASS);
        hDataSource.setConnectionTestQuery(CONNECTION_TEST_QUERY);
        hDataSource.setConnectionTimeout(30000);
        hDataSource.setIdleTimeout(60000);
        hDataSource.setMaxLifetime(1800000);
        hDataSource.setMaximumPoolSize(10);

        Properties p = new Properties();
        p.setProperty("url", localUrl);
        p.setProperty("user", userName);
        p.setProperty("password", password);
        p.setProperty("useUnicode", "true");
        p.setProperty("characterEncoding", "UTF-8");
        p.setProperty("zeroDateTimeBehavior", "convertToNull");
        hDataSource.setDataSourceProperties(p);

        dataSourceMap.put(sourceKey, hDataSource);
        return dataSourceMap;
    }

    public void setDataSourceKey(int sid){
        dsKey.set(sid);
    }

    public Integer getDataSourceKey(){
        return dsKey.get();
    }
}
